package com.liush.common.helper;

import com.liush.model.controller.SysMenu;

import java.util.ArrayList;
import java.util.List;

/**
 * 根据菜单数据构建菜单树的工具类
 */
public class MenuHelper {

    /**
     * 使用递归方法建菜单
     *
     * @param sysMenusAllList
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenusAllList) {
        List<SysMenu> menuTreeList = new ArrayList<>();
        sysMenusAllList.forEach(sysMenu -> {
            if (sysMenu.getParentId() == 0) {
                menuTreeList.add(findChildren(sysMenu, sysMenusAllList));
            }
        });
        return menuTreeList;
    }

    /**
     * 递归查找子节点
     *
     * @param sysMenu,sysMenusAllList
     * @return
     */
    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenusAllList) {
        sysMenu.setChildren(new ArrayList<>());
        sysMenusAllList.forEach(menuChildNode -> {
            if (menuChildNode.getParentId() == sysMenu.getId()) {
                if (sysMenu.getChildren() == null) {
                    sysMenu.setChildren(new ArrayList<>());
                }
                sysMenu.getChildren().add(findChildren(menuChildNode, sysMenusAllList));
            }
        });
        return sysMenu;
    }
}
